use tokio::net::TcpListener;
use tokio::io::AsyncReadExt;
use anyhow::Result;
use dotenv::dotenv;
use std::env;

#[tokio::main]
async fn main() -> Result<()> {
    // 加载 .env 文件
    dotenv().ok();
    
    println!("开始监听网络端口...");
    
    // 创建 TCP 监听器，监听 8080 端口
    // let listener = TcpListener::bind("127.0.0.1:8080").await?;
    let port = env::var("LISTEN_PORT").unwrap_or_else(|_| "8080".to_string());
    let addr = format!("127.0.0.1:{}", port);
    let listener = TcpListener::bind(&addr).await?;
    println!("正在监听端口 {}", port);

    loop {
        let (mut socket, _) = listener.accept().await?;
        
        // 创建缓冲区读取数据
        let mut buffer = [0; 1024];
        let n = socket.read(&mut buffer).await?;
        let message = String::from_utf8_lossy(&buffer[..n]);
        
        match message.trim() {
            "online" => {
                println!("收到在线信号");
                update_wallpaper(true)?;
            },
            "offline" => {
                println!("收到离线信号");
                update_wallpaper(false)?;
            },
            _ => println!("收到未知信号: {}", message),
        }
    }
}


fn update_wallpaper(is_connected: bool) -> Result<()> {
    let wallpaper_path = if is_connected {
        env::var("ONLINE_WALLPAPER").expect("未设置 ONLINE_WALLPAPER 环境变量")
    } else {
        env::var("OFFLINE_WALLPAPER").expect("未设置 OFFLINE_WALLPAPER 环境变量")
    };

    
    // The supported desktops are:
    // Windows
    // macOS
    // GNOME
    // KDE
    // Cinnamon
    // Unity
    // Budgie
    // XFCE
    // LXDE
    // MATE
    // Deepin
    // Most Wayland compositors (set only, requires swaybg)
    // i3 (set only, requires feh)
    // 设置壁纸并确保错误是 Send + Sync
    wallpaper::set_from_path(wallpaper_path.as_str())
        .map_err(|e| anyhow::anyhow!("{}", e))?;
    
    println!("壁纸已更新: {}", if is_connected { "在线" } else { "离线" });
    Ok(())
}


#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_update_wallpaper() {
        dotenv().ok();
        let on_wp = env::var("ONLINE_WALLPAPER").expect("未设置 ONLINE_WALLPAPER 环境变量");
        let off_wp = env::var("OFFLINE_WALLPAPER").expect("未设置 OFFLINE_WALLPAPER 环境变量");

        update_wallpaper(true).unwrap();
        let wp = wallpaper::get().unwrap();
        println!("当前壁纸: {}", wp);
        assert!(wp.contains(&on_wp));

        update_wallpaper(false).unwrap();
        let wp = wallpaper::get().unwrap();
        println!("当前壁纸: {}", wp);
        assert!(wp.contains(&off_wp));
    }

    // fn test_web_server() {
    //     let listener = TcpListener::bind("127.0.0.1:8080").await?;
    //     println!("正在监听端口 8080");
    // }
}